package com.winter.boot.aop;

import com.winter.boot.config.BeanPostProcessor;
import com.winter.boot.config.DefaultBeanPostProcessor;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class BeanProxy implements MethodInterceptor {

    public final static List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    static {
        beanPostProcessors.add(new DefaultBeanPostProcessor());
    }

    private BeanProxy() {
    }

    private static class SingleInstance {
        private static final BeanProxy INSTANCE = new BeanProxy();
    }

    public static BeanProxy getProxyInstance() {
        return SingleInstance.INSTANCE;
    }

    public Object getProxy(Object o) {
        Enhancer enhancer = new Enhancer();  // 通过CGLIB动态代理获取代理对象的过程
        enhancer.setSuperclass(o.getClass());     // 设置enhancer对象的父类
        enhancer.setCallback(this);    // 设置enhancer的回调对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
            beanPostProcessor.postProcessBeforeInitialization(o, o.getClass().getName());
        }
        Object bean = methodProxy.invokeSuper(o, objects);
        for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
            beanPostProcessor.postProcessAfterInitialization(bean, o.getClass().getName());
        }
        return bean;
    }
}
